package com.omega.controller;

import java.util.Iterator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.omega.constants.ApplicationConstants;
import com.omega.entity.MeasuringUnit;
import com.omega.service.MeasuringUnitService;
import com.omega.vo.EntityListVO;
import com.omega.vo.MeasuringUnitListVO;

@Controller
@RequestMapping(value = "/admin/measuringUnit")
public class MeasuringUnitController {
	
	@Autowired
	MeasuringUnitService measuringUnitService;
	
	@RequestMapping(value = "/addNewMeasuringUnit", method = RequestMethod.GET)
	public String showAddMUForm(Model model){
		MeasuringUnitListVO measuringUnitListVO = EntityListVO.getMeasuringUnitListVO(); 
		model.addAttribute(ApplicationConstants.MEASURING_UNIT_LIST_VO, measuringUnitListVO);
		return ApplicationConstants.ADD_NEW_MEASURINGUNIT_VIEW;
	}
	
	@RequestMapping(value = "/addNewMeasuringUnit", method = RequestMethod.POST)
	public String saveAddMUForm(@ModelAttribute(ApplicationConstants.MEASURING_UNIT_LIST_VO) MeasuringUnitListVO measuringUnitListVO){
		for (Iterator<MeasuringUnit> iterator = measuringUnitListVO.getMeasuringUnitList().iterator(); iterator.hasNext();) {
			MeasuringUnit measuringUnit = (MeasuringUnit) iterator.next();
			if(! StringUtils.isEmpty(measuringUnit.getMeasuringUnitValue()))
			measuringUnitService.addMeasuringUnit(measuringUnit);
		}
		return ApplicationConstants.REDIRECT_MEASURING_UNITS_VIEW;
	}
	
	@RequestMapping(value = "/viewMeasuringUnits", method = RequestMethod.GET)
	public String showAllMU(Model model){
		model.addAttribute(ApplicationConstants.MEASURINGUNITS, measuringUnitService.loadAllMeasuringUnits());
		return ApplicationConstants.MEASURING_UNITS_VIEW;
	}
	
	@RequestMapping(value = "/editMeasuringUnit/{measuringUnitId}", method = RequestMethod.GET)
	public String showEditMUForm(@PathVariable("measuringUnitId") String measuringUnitId, Model model){
		MeasuringUnit measuringUnit = measuringUnitService.loadById(Integer.parseInt(measuringUnitId));
		model.addAttribute(ApplicationConstants.MEASURING_UNIT_OBJ, measuringUnit);
		return ApplicationConstants.EDIT_MEASURING_UNIT_VIEW;
	}

	@RequestMapping(value = "/editMeasuringUnit/{measuringUnitId}", method = RequestMethod.POST)
	public String saveEditMUForm(@ModelAttribute(ApplicationConstants.MEASURING_UNIT_OBJ) MeasuringUnit measuringUnit){
		measuringUnitService.updateMeasuringUnit(measuringUnit);
		return ApplicationConstants.REDIRECT_MEASURING_UNITS_VIEW;
	}
}
